// Copyright 2019 Red Hat, Inc. and/or its affiliates
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package converter

import (
	"github.com/kiegroup/kogito-operator/cmd/kogito/command/util"
	"github.com/kiegroup/kogito-operator/core/framework"
	v1 "k8s.io/api/core/v1"
	"strings"
)

// FromStringArrayToEnvs converts a string array in the format of key=value pairs to the required type for the Kubernetes EnvVar type
func FromStringArrayToEnvs(keyPairStrings []string, secretKeyPairStrings []string) (envVars []v1.EnvVar) {
	if len(keyPairStrings) > 0 {
		keyPairMap := util.FromStringsKeyPairToMap(keyPairStrings)
		for key, value := range keyPairMap {
			envVars = append(envVars, framework.CreateEnvVar(key, value))
		}
	}

	if len(secretKeyPairStrings) > 0 {
		keyPairMap := util.FromStringsKeyPairToMap(secretKeyPairStrings)
		for key, value := range keyPairMap {
			if strings.Contains(value, util.SecretNameKeySeparator) {
				secretNameKeyPair := strings.SplitN(value, util.SecretNameKeySeparator, 2)
				if len(secretNameKeyPair) == 2 {
					secretName := secretNameKeyPair[0]
					secretKey := secretNameKeyPair[1]
					secretEnvVar := framework.CreateSecretEnvVar(key, secretName, secretKey)
					envVars = append(envVars, secretEnvVar)
				}
			}
		}
	}
	return envVars
}
